<template>
  <div style="padding: 10px 1vw;">

    <div style="margin-bottom: 20px;text-align: right;">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <el-form ref="form" :model="form" :rules="rules" label-width="180px">
      <el-row>
        <el-col :span="11">
          <el-form-item label="项目编号" prop="taskId" style="width: 80%;">
            <el-input v-model="form.taskId" placeholder="请输入项目编号"/>
          </el-form-item>

          <el-form-item label="项目类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择项目类型">
              <el-option
                v-for="dict in dict.type.villages_project_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目类别" prop="projectCategory">
            <el-select v-model="form.projectCategory" placeholder="请选择项目类别">
              <el-option
                v-for="dict in dict.type.village_project_category"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目级别" prop="projectMold">
            <el-select v-model="form.projectMold" placeholder="请选择项目级别">
              <el-option
                v-for="dict in dict.type.village_achievement_rank"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目名称" prop="location" style="width: 80%;">
            <el-input v-model="form.location" placeholder="请输入项目名称"/>
          </el-form-item>
          <el-form-item label="项目主持人" prop="programLeader" style="width: 80%;">
            <el-input v-model="form.programLeader" placeholder="请输入项目主持人"/>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone" style="width: 80%;">
            <el-input v-model="form.phone" placeholder="请输入联系电话"/>
          </el-form-item>

          <el-form-item label="校级配套经费" prop="schoolSupportingFunds" style="width: 70%;">
            <el-input v-model="form.schoolSupportingFunds" placeholder="请输入配套经费"/>
          </el-form-item>
          <el-form-item label="市级配套经费" prop="citySupportingFunds" style="width: 70%;">
            <el-input v-model="form.citySupportingFunds" placeholder="请输入配套经费"/>
          </el-form-item>
          <el-form-item label="项目总经费" prop="projectFund" style="width: 70%;">
            <el-input disabled placeholder="请输入项目经费" :value="calculateTotalSupportingFunds()"/>
          </el-form-item>

        </el-col>
        <el-col :span="2" style="height: 616px;display: flex;justify-content: center">
          <div style="height: 100%;width: 1px;background-color: #9f9f9f"></div>
        </el-col>
        <el-col :span="11">
          <el-form-item label="项目预算详情" style="width: 80%;">
            <el-button type="primary" @click="projectbudgetopen=true" icon="el-icon-plus"></el-button>
          </el-form-item>

          <el-dialog :visible.sync="projectbudgetopen" width="650px" append-to-body>
            <el-divider content-position="center">教研项目预算信息</el-divider>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddVillageProjectMoney">添加
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteVillageProjectMoney">
                  删除
                </el-button>
              </el-col>
            </el-row>
            <el-table :data="villageProjectMoneyList" :row-class-name="rowVillageProjectMoneyIndex"
                      @selection-change="handleVillageProjectMoneySelectionChange" ref="villageProjectMoney"
            >
              <el-table-column type="selection" width="50" align="center"/>
              <el-table-column label="编号" align="center" width="100">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>

              <el-table-column label="预算名称" align="center" prop="name" width="250">
                <template slot-scope="scope">
                  <el-autocomplete
                    class="inline-input"
                    v-model="scope.row.name"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入内容"
                    @select="((item)=>{unitHandleSelect(item, scope.row)})"

                  ></el-autocomplete>
                </template>
              </el-table-column>

              <el-table-column label="金额" align="center" prop="money" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.money" placeholder="请输入金额"/>
                </template>
              </el-table-column>

            </el-table>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="projectbudgetopen = false">确 定</el-button>
            </div>
          </el-dialog>


          <el-form-item label="单位名称" prop="nameOfWorkingUnit" style="width: 80%;">
            <el-input v-model="form.nameOfWorkingUnit" placeholder="请输入单位名称"/>
          </el-form-item>
          <el-form-item label="通信地址" prop="mailingAddress" style="width: 80%;">
            <el-input v-model="form.mailingAddress" placeholder="请输入通信地址"/>
          </el-form-item>
          <el-form-item label="邮政编码" prop="postalCode" style="width: 80%;">
            <el-input v-model="form.postalCode" placeholder="请输入邮政编码"/>
          </el-form-item>

          <el-form-item label="邮箱" prop="eMail" style="width: 80%;">
            <el-input v-model="form.eMail" placeholder="请输入邮箱"/>
          </el-form-item>


          <el-form-item label="立项时间" prop="projectApprovalTime">
            <el-date-picker clearable v-model="form.projectApprovalTime" type="date"
                            value-format="yyyy-MM-dd" placeholder="请选择立项时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="经费类型" prop="supportingFundsType">
            <el-select v-model="form.supportingFundsType" placeholder="请选择经费类型">
              <el-option v-for="dict in dict.type.village_ongoing_development" :key="dict.value"
                         :label="dict.label" :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目状态" prop="projectStatus">
            <el-radio-group v-model="form.projectStatus">
              <el-radio
                v-for="dict in dict.type.village_project_status"
                :key="dict.value"
                :label="parseInt(dict.value)"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="开始时间" prop="beginTime">
            <el-date-picker clearable v-model="form.beginTime" type="date" value-format="yyyy-MM-dd"
                            placeholder="请选择开始时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="截止时间" prop="cutOffTime">
            <el-date-picker clearable v-model="form.cutOffTime" type="date" value-format="yyyy-MM-dd"
                            placeholder="请选择截止时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="资料上传列表：" prop="cutOffTime">
            <el-button type="primary" @click="dataopen = true">上传资料</el-button>
          </el-form-item>


          <el-dialog title="资料上传" :visible.sync="dataopen" width="900px" append-to-body>
            <el-form-item label="立项申请书" prop="resignationLetter">
              <file-upload :openUplad="true" style="width: 500px" :isShowTip="false" v-model="form.resignationLetter"/>
            </el-form-item>
            <el-form-item label="任务书" prop="task">
              <file-upload :openUplad="true" style="width: 500px" :isShowTip="false" v-model="form.task"/>
            </el-form-item>
            <el-form-item label="开题报告" prop="proposalMaterial">
              <file-upload :openUplad="true" style="width: 500px" :isShowTip="false" v-model="form.proposalMaterial"/>
            </el-form-item>
            <el-form-item label="中期报告" prop="interimReport">
              <file-upload :openUplad="true" style="width: 500px" :isShowTip="false" v-model="form.interimReport"/>
            </el-form-item>
            <el-form-item label="变更材料" prop="changeOfMaterial">
              <file-upload :openUplad="true" style="width: 500px" :isShowTip="false" v-model="form.changeOfMaterial"/>
            </el-form-item>
            <el-form-item label="研究报告" prop="studyReport">
              <file-upload :openUplad="true" style="width: 500px" :isShowTip="false" v-model="form.studyReport"/>
            </el-form-item>
            <el-form-item label="结题材料" prop="finishingMaterials">
              <file-upload :openUplad="true" style="width: 500px" :isShowTip="false" v-model="form.finishingMaterials"/>
            </el-form-item>
            <el-form-item label="佐证材料" prop="supportingMaterial">
              <file-upload :openUplad="true" style="width: 500px" :isShowTip="false" v-model="form.supportingMaterial"/>
            </el-form-item>


            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="dataopen = false">确 定</el-button>
            </div>
          </el-dialog>

        </el-col>

      </el-row>
    </el-form>
  </div>
</template>

<script>
import { listReform, getReform, delReform, addReform, updateReform } from '@/api/village/reform'
import { noListManage} from '@/api/village/manage'
import item from '@/layout/components/Sidebar/Item.vue'

export default {
  name: 'Change',
  dicts: ['village_project_status', 'village_achievement_rank', 'villages_project_type', 'village_project_category', 'village_ongoing_development'],

  data() {
    return {
      restaurants: [],
      money: {},
      expenselist: [],
      villageProjectMoneyList: [],
      checkedVillageProjectMoney: [],
      projectbudgetopen: false,
      dataopen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教改项目表格数据
      reformList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supportingFundsType: null
      },
      // 表单参数
      form: {

        projectStatus: 1
      },
      // 表单校验
      rules: {
        type: [
          { required: true, message: '项目类型不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}|^(\+\d{1,4})?[-\s]?(\(?\d{1,4}\)?[-\s]?)?\d{1,4}[-\s]?\d{1,4}([-\s]?\d{1,9})?$/, // 正则表达式，匹配中国手机号格式
            message: '请输入正确的手机号码',
            trigger: ['input', 'blur']
          }
        ],
        location: [
          { required: true, message: '项目名称不能为空', trigger: 'blur' }
        ],
        projectMold: [
          { required: true, message: '项目级别不能为空', trigger: 'blur' }
        ],
        projectCategory: [
          { required: true, message: '项目类别不能为空', trigger: 'blur' }
        ],

        taskId:[
          { required: true, message: '项目编号不能为空', trigger: 'blur' }
        ],
        programLeader: [
          { required: true, message: '项目主持人不能为空', trigger: 'blur' }
        ],
        projectApprovalTime: [
          { required: true, message: '立项时间不能为空', trigger: 'blur' }
        ],
        postalCode: [
          {
            pattern: /^\d{6}$/, // 正则表达式，匹配6位数字的邮政编码
            message: '请输入正确的6位邮政编码',
            trigger: ['input', 'blur']
          }
        ],
        eMail: [
          {
            pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, // 验证电子邮件地址的正则表达式
            message: '请输入有效的电子邮箱地址',
            trigger: ['input', 'blur']
          }
        ],
        schoolSupportingFunds: [
          { required: true, message: '校级配套经费不能为空', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d+)?$/, // 正则表达式，匹配一个或多个数字，后面可跟一个小数点和一个或多个数字
            message: '请输入数字',
            trigger: ['input', 'blur']
          }
        ],
        citySupportingFunds: [
          { required: true, message: '市级配套经费不能为空', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d+)?$/, // 正则表达式，匹配一个或多个数字，后面可跟一个小数点和一个或多个数字
            message: '请输入数字',
            trigger: ['input', 'blur']
          }
        ]
      }
    }
  },
  created() {
    if (this.$route.query.id != null) {
      this.handleUpdate(this.$route.query)
    }
    this.getList()
  },
  mounted() {

  },
  methods: {
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {

      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    loadAll() {

      return this.expenselist

    },
    unitHandleSelect(item,row) {

      row.money = item.address
    },

    rowVillageProjectMoneyIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 教研项目预算添加按钮操作 */
    handleAddVillageProjectMoney() {
      let obj = {}

      obj.name = ''
      obj.money = ''
      obj.remark = ''
      obj.isDelete = ''
      this.villageProjectMoneyList.push(obj)
    },
    /** 教研项目预算删除按钮操作 */
    handleDeleteVillageProjectMoney() {
      if (this.checkedVillageProjectMoney.length == 0) {
        this.$modal.msgError('请先选择要删除的教研项目预算数据')
      } else {
        const villageProjectMoneyList = this.villageProjectMoneyList

        const checkedVillageProjectMoney = this.checkedVillageProjectMoney
        this.villageProjectMoneyList = villageProjectMoneyList.filter(function(item) {
          return checkedVillageProjectMoney.indexOf(item.index) == -1
        })

      }
    },
    /** 复选框选中数据 */
    handleVillageProjectMoneySelectionChange(selection) {
      this.checkedVillageProjectMoney = selection.map(item => item.index)
    },
    calculateTotalSupportingFunds() {
      let schoolFunds = parseFloat(this.form.schoolSupportingFunds)
      let cityFunds = parseFloat(this.form.citySupportingFunds)

      // 更清晰的三目运算符分离，确保每个数值转换并处理NaN
      schoolFunds = isNaN(schoolFunds) ? 0 : schoolFunds
      cityFunds = isNaN(cityFunds) ? 0 : cityFunds

      // 明确的相加操作
      let totalFunds = schoolFunds + cityFunds

      this.form.projectFund = totalFunds

      return totalFunds.toFixed()
    },
    /** 查询教改项目列表 */
    getList() {
      // this.loading = true
      // listReform(this.queryParams).then(response => {
      //   this.reformList = response.rows
      //   this.total = response.total
      //   this.loading = false
      //   this.form = response.rows[0]
      // })
      noListManage({}).then(response => {

        this.expenselist = response.rows.map(item => ({
          address: item.money,

          value: item.name
        }))
        this.restaurants = this.loadAll()
      })
    },
    // 取消按钮
    cancel() {

      this.$router.push('/Pedagogical')
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskId: null,
        location: null,
        programLeader: null,
        type: null,
        projectCategory: null,
        projectMold: null,
        nameOfWorkingUnit: null,
        mailingAddress: null,
        postalCode: null,
        phone: null,
        eMail: null,
        projectApprovalTime: null,
        projectFund: null,
        schoolSupportingFunds: null,
        citySupportingFunds: null,
        balance: null,
        supportingFundsType: null,
        beginTime: null,
        cutOffTime: null,
        resignationLetter: null,
        task: null,
        proposalMaterial: null,
        interimReport: null,
        finishingMaterials: null,
        supportingMaterial: null,
        studyReport: null,
        changeOfMaterial: null,
        createTime: null,
        projectStatus: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        isDelete: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加教改项目'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getReform(id).then(response => {
        this.form = response.data
        this.open = true
        this.villageProjectMoneyList = response.data.villageProjectMoneyList
        this.title = '修改教改项目'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.villageProjectMoneyList = this.villageProjectMoneyList
          if (this.form.id != null) {
            updateReform(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
              this.$router.go(-1)
            })
          } else {
            addReform(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
              this.$router.go(-1)
            })
          }
        }
      })

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除教改项目编号为"' + ids + '"的数据项？').then(function() {
        return delReform(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('village/reform/export', {
        ...this.queryParams
      }, `reform_${new Date().getTime()}.xlsx`)
    },
    // 详情
    skipDetail(row) {
      this.$router.push(`/Pedagogicaldetail?id=${row.id}`)
    }
  }
}
</script>

<style>
.upload-file .upload-file-uploader {
  display: block;
}
</style>
